package com.norma.macaron.service.gateway.filter;

import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.norma.macaron.service.gateway.service.AuthService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/***
 * @Author zhangchaofeng
 * @Description 全局Filter，统一处理登录与外部不允许访问的服务
 * @Date 19:51 2020/6/9 0009
 **/
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    Logger log = LoggerFactory.getLogger(AuthGlobalFilter.class);

    @Autowired
    AuthService authService;

    private static final List<String> AUTHORIZED_URI = Lists.newArrayList("/**/login", "/**/logout", "/**/jwt");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        log.info("--------------->url = [{}]", path);
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        List<String> filter_res = AUTHORIZED_URI.stream().filter(x -> antPathMatcher.match(x, path)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(filter_res)) {
            //免过滤接口放行
            return chain.filter(exchange);
        }
        //内部服务接口，不允许外部访问
        if (antPathMatcher.match("/**/inner/**", path)) {
            return out(response);
        }
        String token = authService.getAccessToken(request);
        if (StringUtils.isBlank(token)) {
            //拒绝访问
            return out(response);
        }
        //从header中取jwt
        String jwtFromHeader = authService.getJwtFromHeader(request);
        if (StringUtils.isEmpty(jwtFromHeader)) {
            //拒绝访问
            return out(response);
        }
        //从redis取出jwt的过期时间
        long expire = authService.getExpire(token);
        if (expire < 0) {
            //拒绝访问
            return out(response);
        }
        log.info("------------->Go! Call interface,path=[{}]", path);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("code", HttpStatus.UNAUTHORIZED.value());
        message.addProperty("message", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        /**指定编码，否则在浏览器中会中文乱码*/
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
